import {
    pgTable,
    bigint,
    text,
    timestamp,
    boolean,
    jsonb,
    integer,
    smallint,
    date,
    uuid,
    pgEnum,
} from "drizzle-orm/pg-core"
import { authUsers } from "./auth_users"
import {lockedTenantEnum} from "./enums";

export const tenants = pgTable(
    "tenants",
    {
        id: bigint("id", { mode: "number" })
            .primaryKey()
            .generatedByDefaultAsIdentity(),

        createdAt: timestamp("created_at", { withTimezone: true })
            .notNull()
            .defaultNow(),

        name: text("name").notNull(),
        short: text("short").notNull(),

        calendarConfig: jsonb("calendarConfig").default({
            eventTypes: [
                { color: "blue", label: "Büro" },
                { color: "yellow", label: "Besprechung" },
                { color: "green", label: "Umsetzung" },
                { color: "red", label: "Vor Ort Termin" },
            ],
        }),

        timeConfig: jsonb("timeConfig").notNull().default({}),

        tags: jsonb("tags").notNull().default({
            products: [],
            documents: [],
        }),

        measures: jsonb("measures")
            .notNull()
            .default([
                { name: "Netzwerktechnik", short: "NWT" },
                { name: "Elektrotechnik", short: "ELT" },
                { name: "Photovoltaik", short: "PV" },
                { name: "Videüberwachung", short: "VÜA" },
                { name: "Projekt", short: "PRJ" },
                { name: "Smart Home", short: "SHO" },
            ]),

        businessInfo: jsonb("businessInfo").default({
            zip: "",
            city: "",
            name: "",
            street: "",
            email: "",
            phone: "",
            website: "",
            taxNumber: "",
            vatId: "",
            bankName: "",
            bankAccountOwner: "",
            iban: "",
            bic: "",
        }),

        features: jsonb("features").default({
            objects: true,
            calendar: true,
            contacts: true,
            projects: true,
            vehicles: true,
            contracts: true,
            inventory: true,
            accounting: true,
            timeTracking: true,
            planningBoard: true,
            workingTimeTracking: true,
            dashboard: true,
            historyitems: true,
            tasks: true,
            wiki: true,
            files: true,
            createdletters: true,
            documentboxes: true,
            helpdesk: true,
            email: true,
            members: true,
            customers: true,
            vendors: true,
            contactsList: true,
            staffTime: true,
            createDocument: true,
            serialInvoice: true,
            incomingInvoices: true,
            outgoingsepamandates: true,
            costcentres: true,
            branches: true,
            teams: true,
            accounts: true,
            ownaccounts: true,
            banking: true,
            spaces: true,
            customerspaces: true,
            customerinventoryitems: true,
            inventoryitems: true,
            inventoryitemgroups: true,
            products: true,
            productcategories: true,
            services: true,
            servicecategories: true,
            memberrelations: true,
            staffProfiles: true,
            hourrates: true,
            projecttypes: true,
            contracttypes: true,
            plants: true,
            settingsNumberRanges: true,
            settingsEmailAccounts: true,
            settingsBanking: true,
            settingsTexttemplates: true,
            settingsTenant: true,
            export: true,
        }),

        ownFields: jsonb("ownFields"),

        numberRanges: jsonb("numberRanges")
            .notNull()
            .default({
                vendors: { prefix: "", suffix: "", nextNumber: 10000 },
                customers: { prefix: "", suffix: "", nextNumber: 10000 },
                products: { prefix: "AT-", suffix: "", nextNumber: 1000 },
                quotes: { prefix: "AN-", suffix: "", nextNumber: 1000 },
                costEstimates: { prefix: "KS-", suffix: "", nextNumber: 1000 },
                confirmationOrders: { prefix: "AB-", suffix: "", nextNumber: 1000 },
                invoices: { prefix: "RE-", suffix: "", nextNumber: 1000 },
                deliveryNotes: { prefix: "LS-", suffix: "", nextNumber: 1000 },
                packingSlips: { prefix: "PS-", suffix: "", nextNumber: 1000 },
                spaces: { prefix: "LP-", suffix: "", nextNumber: 1000 },
                customerspaces: { prefix: "KLP-", suffix: "", nextNumber: 1000 },
                inventoryitems: { prefix: "IA-", suffix: "", nextNumber: 1000 },
                customerinventoryitems: { prefix: "KIA-", suffix: "", nextNumber: 1000 },
                projects: { prefix: "PRJ-", suffix: "", nextNumber: 1000 },
                costcentres: { prefix: "KST-", suffix: "", nextNumber: 1000 },
                outgoingsepamandates: { prefix: "SEPA-", suffix: "", nextNumber: 1000 },
            }),
        accountChart: text("accountChart").notNull().default("skr03"),

        standardEmailForInvoices: text("standardEmailForInvoices"),

        extraModules: jsonb("extraModules").notNull().default([]),

        isInTrial: boolean("isInTrial").default(false),
        trialEndDate: date("trialEndDate"),

        stripeCustomerId: text("stripeCustomerId"),

        hasActiveLicense: boolean("hasActiveLicense").notNull().default(false),

        userLicenseCount: integer("userLicenseCount")
            .notNull()
            .default(0),

        workstationLicenseCount: integer("workstationLicenseCount")
            .notNull()
            .default(0),

        standardPaymentDays: smallint("standardPaymentDays")
            .notNull()
            .default(14),

        taxEvaluationPeriod: text("taxEvaluationPeriod")
            .notNull()
            .default("monthly"),

        dokuboxEmailAddresses: jsonb("dokuboxEmailAddresses").default([]),

        dokuboxkey: uuid("dokuboxkey").notNull().defaultRandom(),

        autoPrepareIncomingInvoices: boolean("autoPrepareIncomingInvoices")
            .default(true),

        portalDomain: text("portalDomain"),

        portalConfig: jsonb("portalConfig")
            .notNull()
            .default({ primayColor: "#69c350" }),

        updatedAt: timestamp("updated_at", { withTimezone: true }),
        updatedBy: uuid("updated_by").references(() => authUsers.id),

        locked: lockedTenantEnum("locked"),
        lockedByExportJobId: uuid("locked_by_export_job_id"),
    }
)

export type Tenant = typeof tenants.$inferSelect
export type NewTenant = typeof tenants.$inferInsert
