from datetime import date, timedelta

from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
from django.utils import timezone

from core.models import (CalendarEvent, Client, Invoice, InvoiceItem, Lead,
                         Milestone, OngoingService, Payment, PortfolioCategory,
                         PortfolioProject, PricingPackage, ProcessStep, Project,
                         ProjectUpdate, Quote, QuoteItem, Service, SiteSettings,
                         Statistic, Task, Testimonial, Ticket, Website,
                         WebsiteActivity, WebsiteCredential)


class Command(BaseCommand):
    help = "Seed the database with the demo content used in the prototypes."

    def handle(self, *args, **options):
        today = timezone.localdate()

        site = SiteSettings.load()
        site.name = "Teniteno1"
        site.tagline = "Web developer · Software developer · Founder"
        site.contact_email = "hello@teniteno1.com"
        site.whatsapp = "+234 800 000 0000"
        site.location = "Lagos, Nigeria"
        site.meta_description = ("Websites, web applications and payment platforms, "
                                 "built and maintained from Lagos.")
        site.payment_provider = "dSociopay"
        site.webhook_url = "https://teniteno1.com/webhooks/payments/"
        site.save()

        owner, created = User.objects.get_or_create(
            username="teniola@teniteno1.com",
            defaults={"email": "teniola@teniteno1.com", "first_name": "Teniola",
                      "last_name": "Ayodele", "is_staff": True, "is_superuser": True},
        )
        if created:
            owner.set_password("changeme123")
            owner.save()
            self.stdout.write("Owner account: teniola@teniteno1.com / changeme123")

        for value, label, order in [("40+", "Projects delivered", 1), ("25+", "Clients served", 2),
                                    ("5 yrs", "Building for the web", 3), ("6", "Sites under management", 4)]:
            Statistic.objects.get_or_create(label=label, defaults={"value": value, "order": order})

        steps = [
            ("Consultation", "A call to understand the business, the customers and what success looks like."),
            ("Requirements", "Everything written down and agreed before a line of code — scope, features, price, dates."),
            ("Design", "You approve the look and the page structure first."),
            ("Development", "Frontend and backend built against the agreed milestones."),
            ("Testing", "Devices, forms, payments, load and security checks."),
            ("Launch", "Domain, hosting, SSL and deployment handled for you."),
            ("Support", "Monitoring, updates and changes on an ongoing plan."),
        ]
        for i, (title, description) in enumerate(steps, start=1):
            ProcessStep.objects.get_or_create(title=title, defaults={"description": description, "order": i})

        services = [
            ("Business websites", "business-websites", "A site that explains what you do and turns visitors into enquiries.",
             "Custom design\nUp to 15 pages\nContent dashboard\nContact forms\nSEO setup", "From ₦350,000", "1–3 weeks"),
            ("E-commerce stores", "ecommerce", "Sell online with real payments, real stock control and real order management.",
             "Product catalogue\nCart and checkout\nPayment integration\nOrder management\nDelivery options", "From ₦1,200,000", "4–6 weeks"),
            ("Web applications", "web-applications", "Dashboards, portals and SaaS platforms built around how your business works.",
             "User accounts and roles\nCustom dashboards\nAdmin system\nReporting\nAPI access", "From ₦1,800,000", "6–10 weeks"),
            ("Payment & fintech platforms", "fintech", "Collections, wallets, virtual accounts and payouts — built and reconciled correctly.",
             "Gateway integration\nWebhook handling\nWallet and ledger\nReconciliation reports\nCompliance-ready logs", "Quoted per project", "8–12 weeks"),
            ("Custom software", "custom-software", "Automation and internal tools that replace the spreadsheet everyone is afraid of.",
             "Process automation\nInternal tools\nData migration\nIntegrations\nStaff training", "Quoted per project", "Agreed per scope"),
            ("Website maintenance", "maintenance", "Someone responsible for the site after launch, so problems get found before customers do.",
             "Bug fixes\nUpdates and patches\nUptime monitoring\nDaily backups\nContent changes", "₦25,000 / month", "Ongoing"),
            ("Hosting & deployment", "hosting", "Servers, domains, SSL and deployments handled — registered in your name, not mine.",
             "Managed server\nDomain and DNS\nSSL certificates\nDeployment pipeline\nRenewal tracking", "₦60,000 / year", "Set up in 48 hours"),
            ("API integration", "api-integration", "Connecting your site to the payment, delivery or messaging services you already use.",
             "Third-party integrations\nWebhook endpoints\nError handling and retries\nAPI documentation\nTesting", "From ₦250,000", "1–2 weeks"),
        ]
        for i, (title, slug, summary, included, price, delivery) in enumerate(services, start=1):
            Service.objects.get_or_create(slug=slug, defaults={
                "title": title, "summary": summary, "included": included,
                "starting_price": price, "delivery_time": delivery, "order": i})

        packages = [
            ("Starter", "starter", "For individuals and small businesses getting online properly.", "₦350,000",
             "one-off · from", "Delivered in 1–2 weeks",
             "Up to 5 pages\nMobile-first responsive design\nContact form with email alerts\nWhatsApp and social links\n"
             "Basic SEO setup\nFree domain and hosting, first year\nSSL certificate\n30 days of post-launch support", False),
            ("Business", "business", "For established businesses that need the site to do real work.", "₦850,000",
             "one-off · from", "Delivered in 3–4 weeks",
             "Up to 15 pages\nCustom design, no template\nContent management dashboard\nBlog or news section\n"
             "Online payment collection\nGoogle Analytics and search setup\nFree domain and hosting, first year\n"
             "90 days of post-launch support", True),
            ("Professional", "professional", "For platforms, marketplaces and custom systems.", "₦2,500,000",
             "project · from", "Timeline agreed per project",
             "Unlimited pages and screens\nUser accounts and dashboards\nPayment and fintech integration\n"
             "Admin system built for your workflow\nAPI development and integrations\nLoad and security testing\n"
             "Staging and production servers\n6 months of support included", False),
        ]
        for i, (name, slug, audience, price, note, delivery, features, featured) in enumerate(packages, start=1):
            PricingPackage.objects.get_or_create(slug=slug, defaults={
                "name": name, "audience": audience, "price": price, "price_note": note,
                "delivery_time": delivery, "features": features, "featured": featured, "order": i})

        ongoing = [
            ("Website maintenance", "Updates, bug fixes, backups, uptime monitoring, small content changes", "₦25,000 / month"),
            ("Managed hosting", "Server, deployment, SSL renewal, daily backups", "₦60,000 / year"),
            ("Domain registration", ".com, .ng, .com.ng — registered and renewed in your name", "From ₦18,000 / year"),
            ("E-commerce store", "Products, cart, checkout, payments, order management", "From ₦1,200,000"),
            ("Web application", "Dashboards, portals, SaaS platforms, internal tools", "From ₦1,800,000"),
            ("Custom software & APIs", "Business automation, integrations, bespoke systems", "Quoted per project"),
        ]
        for i, (name, covers, price) in enumerate(ongoing, start=1):
            OngoingService.objects.get_or_create(name=name, defaults={"covers": covers, "price": price, "order": i})

        quotes_said = [
            ("We had been quoted twice as much for half of this. The store went live in three weeks and card payments worked from day one.",
             "Chidinma O.", "Founder, retail brand"),
            ("He rebuilt our booking system and explained every part in plain English. Two years later he still answers when something needs changing.",
             "Dr. Aliyu B.", "Clinic director"),
            ("The portal means I can see exactly where my project is without calling anyone. That alone was worth it.",
             "Emeka N.", "Logistics company"),
        ]
        for i, (quote, author, role) in enumerate(quotes_said, start=1):
            Testimonial.objects.get_or_create(author=author, defaults={"quote": quote, "role": role, "order": i})

        categories = {}
        for name, slug in [("Websites", "websites"), ("Web Apps", "web-apps"), ("E-commerce", "e-commerce"),
                           ("Fintech", "fintech"), ("SaaS", "saas"), ("APIs", "apis")]:
            categories[slug] = PortfolioCategory.objects.get_or_create(slug=slug, defaults={"name": name})[0]

        portfolio = [
            ("dSociopay", "dsociopay", "DSOCIO TECH SOLUTIONS LTD", "fintech",
             "Payment platform for Nigerian businesses — collections, virtual accounts and payouts.",
             "A payment platform handling collections, virtual account generation and payouts for Nigerian "
             "businesses, with a merchant dashboard and a documented API for developers.",
             "Small businesses were stitching together bank transfers and screenshots to confirm payments, "
             "with no record and no way to reconcile at the end of the month.",
             "Card and bank transfer collection\nDedicated virtual accounts\nSigned webhooks with retries\n"
             "Automatic reconciliation and settlement reports\nMerchant dashboard\nPublic API documentation",
             "Backend development, API design, Payment integration, Deployment",
             "Django, PostgreSQL, REST API, Webhooks", "https://getquickcode.com", date(2025, 6, 1), True),
            ("Daisysim", "daisysim", "Own product", "saas",
             "Virtual phone numbers for SMS verification, sold by the code.",
             "A self-serve platform where users rent virtual numbers to receive one-time verification codes, "
             "with wallet top-ups and automatic number release.",
             "Users needed short-lived numbers for verification without buying SIM cards, and existing services "
             "were slow to deliver codes and hard to pay for locally.",
             "Number rental by service and country\nLive code delivery\nWallet with local payment methods\n"
             "Automatic refunds on failed rentals\nProvider failover\nAdmin pricing controls",
             "Full-stack development, Payment integration, Provider integration, Hosting",
             "Django, Celery, Redis, Payments", "https://daisysim.com", date(2025, 9, 1), True),
            ("Theswiftsms", "theswiftsms", "Own product", "saas",
             "SMS verification platform that can switch number providers without downtime.",
             "An SMS verification service built so the underlying number provider can be swapped from the admin "
             "panel — pricing, availability and routing all follow automatically.",
             "Depending on a single number supplier meant outages and price changes hit customers directly.",
             "Switchable provider backends\nUnified pricing layer\nWallet and order history\n"
             "Admin provider controls\nAutomatic order expiry\nUsage reporting",
             "Architecture, Backend development, Integrations, Deployment",
             "Django, REST API, Redis, Payments", "https://theswiftsms.com", date(2026, 2, 1), True),
            ("thespeedkeys", "thespeedkeys", "Own product", "e-commerce",
             "Marketplace for software licences, game codes and gift cards.",
             "A digital goods store delivering licence keys and gift card codes instantly after payment, with "
             "stock control and order history.",
             "Digital key sellers were delivering codes manually over chat, which meant delays, disputes and no "
             "stock visibility.",
             "Instant delivery after payment\nStock and inventory control\nCategory browsing and search\n"
             "Order history and re-delivery\nFraud checks on checkout\nSeller dashboard",
             "Full-stack development, Payment integration, Hosting",
             "Django, PostgreSQL, Payments", "https://thespeedkeys.com", date(2025, 4, 1), True),
        ]
        for (name, slug, client_name, cat, summary, description, problem,
             features, svcs, tech, url, completed, featured) in portfolio:
            PortfolioProject.objects.get_or_create(slug=slug, defaults={
                "name": name, "client_name": client_name, "category": categories[cat],
                "summary": summary, "description": description, "problem": problem,
                "features": features, "services": svcs, "technologies": tech,
                "project_url": url, "completed_on": completed, "featured": featured,
                "published": True})

        # ── a demo client with projects, websites, invoices and support ──
        user, created = User.objects.get_or_create(
            username="chidinma@abc-company.ng",
            defaults={"email": "chidinma@abc-company.ng", "first_name": "Chidinma", "last_name": "Okafor"},
        )
        if created:
            user.set_password("clientdemo123")
            user.save()
            self.stdout.write("Client account: chidinma@abc-company.ng / clientdemo123")
        client, _ = Client.objects.get_or_create(
            user=user, defaults={"company": "ABC Company Ltd", "phone": "+234 802 445 1200"})

        project, made = Project.objects.get_or_create(slug="abc-website", defaults={
            "client": client, "name": "ABC Company Website", "project_type": "Business website",
            "budget": 850000, "status": Project.DEVELOPMENT, "progress": 65,
            "start_date": today - timedelta(days=80), "deadline": today + timedelta(days=30),
            "developer": "Teniola Ayodele",
            "internal_notes": "Client asked for draft publishing at no extra cost — agreed, small change."})
        if made:
            stages = [("Requirements", Milestone.DONE), ("UI design", Milestone.DONE),
                      ("Frontend", Milestone.DONE), ("Backend", Milestone.IN_PROGRESS),
                      ("Testing", Milestone.NOT_STARTED), ("Client approval", Milestone.NOT_STARTED),
                      ("Deployment", Milestone.NOT_STARTED)]
            for i, (title, status) in enumerate(stages, start=1):
                Milestone.objects.create(project=project, title=title, status=status, order=i)
            ProjectUpdate.objects.create(
                project=project, title="Content dashboard",
                body="Staff can now publish news posts and edit the services page. Careers section is next.")
            ProjectUpdate.objects.create(
                project=project, title="Frontend complete",
                body="All 14 pages built and checked on Android, iPhone and desktop.")

        store, made = Project.objects.get_or_create(slug="abc-store", defaults={
            "client": client, "name": "ABC Online Store", "project_type": "E-commerce",
            "budget": 1200000, "status": Project.AWAITING_APPROVAL, "progress": 88,
            "start_date": today - timedelta(days=180), "deadline": today + timedelta(days=20),
            "developer": "Teniola Ayodele"})
        if made:
            ProjectUpdate.objects.create(
                project=store, title="Ready for your review",
                body="Testing is done. The staging link is in your messages — check the checkout with a test card.")

        website, made = Website.objects.get_or_create(slug="abc-company-website", defaults={
            "name": "ABC Company Website", "client": client, "project": project,
            "domain": "abc-company.ng", "status": Website.ONLINE,
            "built_on": today - timedelta(days=10), "last_deployment": today - timedelta(days=3),
            "registrar": "Whogohost", "domain_expiry": today + timedelta(days=42), "auto_renew": True,
            "dns_notes": "A record to srv-04, MX on Google Workspace",
            "hosting_provider": "Managed VPS — Lagos region", "hosting_plan": "2 vCPU / 4 GB",
            "hosting_expiry": today + timedelta(days=400), "server_reference": "srv-04 · NG-LAG-04",
            "backend": "Django · PostgreSQL · Nginx", "frontend": "HTML, CSS, JavaScript",
            "database": "PostgreSQL 16", "apis": "SMTP, Google Analytics",
            "ssl_provider": "Let's Encrypt", "ssl_expiry": today + timedelta(days=160),
            "maintenance_status": Website.MAINT_ACTIVE, "last_update": today - timedelta(days=3),
            "next_maintenance": today + timedelta(days=27)})
        if made:
            WebsiteCredential.objects.create(website=website, label="Server SSH", vault_reference="vault://abc/ssh")
            WebsiteCredential.objects.create(website=website, label="Database", vault_reference="vault://abc/db")
            WebsiteCredential.objects.create(website=website, label="Registrar login",
                                             vault_reference="—", held_by_client=True)
            WebsiteActivity.objects.create(website=website, description="Deployment completed — content dashboard")
            WebsiteActivity.objects.create(website=website, description="SSL renewed automatically")

        deposit, made = Invoice.objects.get_or_create(number="INV-2026-018", defaults={
            "client": client, "project": project, "description": "50% deposit", "total": 425000,
            "status": Invoice.PAID, "issued_on": today - timedelta(days=80),
            "due_on": today - timedelta(days=78)})
        if made:
            InvoiceItem.objects.create(invoice=deposit, description="Deposit on ABC Company Website", amount=425000)
            Payment.objects.create(client=client, project=project, invoice=deposit, amount=425000,
                                   method=Payment.TRANSFER, reference="TRF-8829104",
                                   status=Payment.CONFIRMED, paid_on=today - timedelta(days=78))

        balance, made = Invoice.objects.get_or_create(number="INV-2026-041", defaults={
            "client": client, "project": project, "description": "Balance on delivery", "total": 425000,
            "status": Invoice.SENT, "issued_on": today, "due_on": today + timedelta(days=30)})
        if made:
            InvoiceItem.objects.create(invoice=balance, description="Balance on ABC Company Website", amount=425000)

        store_invoice, made = Invoice.objects.get_or_create(number="INV-2026-009", defaults={
            "client": client, "project": store, "description": "Full project payment", "total": 1200000,
            "status": Invoice.PAID, "issued_on": today - timedelta(days=180),
            "due_on": today - timedelta(days=176)})
        if made:
            Payment.objects.create(client=client, project=store, invoice=store_invoice, amount=1200000,
                                   method=Payment.CARD, reference="PAY-3391077",
                                   status=Payment.CONFIRMED, paid_on=today - timedelta(days=176))

        Ticket.objects.get_or_create(reference="TK-231", defaults={
            "client": client, "project": project, "subject": "Careers page form not sending emails",
            "message": "The careers form says sent but no email arrives.", "priority": Ticket.HIGH,
            "status": Ticket.OPEN})

        leads = [
            ("Ngozi Eze", "Bloom Interiors", "ngozi@bloom.ng", "E-commerce store", "₦1m – ₦3m", Lead.NEW),
            ("Samuel Adeyemi", "Adeyemi Logistics", "sam@adeyemilog.com", "Web application", "₦3m+", Lead.QUOTED),
            ("Fatima Bello", "Bello & Co Legal", "fatima@belloco.ng", "Business website", "₦500,000 – ₦1m", Lead.NEGOTIATING),
            ("Kelechi Umeh", "Umeh Foods", "kelechi@umehfoods.com", "Business website", "Under ₦500,000", Lead.CONTACTED),
        ]
        for name, company, email, ptype, budget, status in leads:
            Lead.objects.get_or_create(email=email, defaults={
                "name": name, "company": company, "project_type": ptype,
                "budget": budget, "status": status, "source": "start-project",
                "description": f"Enquiry from {company}."})

        quote, made = Quote.objects.get_or_create(number="QT-2026-014", defaults={
            "client": client, "title": "Fleet tracking dashboard", "status": Quote.SENT})
        if made:
            for i, (desc, amount) in enumerate([("Design", 400000), ("Frontend", 900000),
                                                ("Backend", 1600000), ("Deployment", 200000)], start=1):
                QuoteItem.objects.create(quote=quote, description=desc, amount=amount, order=i)

        tasks = [
            ("Fix careers form mailer", project, Task.HIGH, Task.IN_PROGRESS, 1),
            ("Draft + scheduled publishing", project, Task.NORMAL, Task.TODO, 5),
            ("Chase store approval", store, Task.NORMAL, Task.REVIEW, 2),
            ("Monthly uptime report", project, Task.LOW, Task.COMPLETED, 30),
        ]
        for name, proj, priority, status, days in tasks:
            Task.objects.get_or_create(name=name, defaults={
                "project": proj, "priority": priority, "status": status,
                "due_date": today + timedelta(days=days)})

        events = [
            ("Okon compliance call, 10:00", "Meeting", 3),
            ("ABC Online Store deployment target", "Project", 20),
            ("ABC maintenance window", "Maintenance", 28),
            ("ABC Company Website delivery deadline", "Project", 30),
        ]
        for title, kind, days in events:
            CalendarEvent.objects.get_or_create(title=title, defaults={
                "kind": kind, "date": today + timedelta(days=days)})

        self.stdout.write(self.style.SUCCESS("Demo content seeded."))
