-- Create company_data table for storing crawled company information
CREATE TABLE IF NOT EXISTS public.company_data (
    id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
    url TEXT NOT NULL,
    company_name TEXT,
    org_number TEXT,
    email TEXT,
    phone TEXT,
    address TEXT,
    postal_code TEXT,
    city TEXT,
    website TEXT,
    crawled_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    status TEXT DEFAULT 'completed',
    raw_html_hash TEXT,
    extraction_confidence REAL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    UNIQUE(url)
);

-- Create indexes for better performance
CREATE INDEX IF NOT EXISTS idx_company_data_url ON public.company_data(url);
CREATE INDEX IF NOT EXISTS idx_company_data_org_number ON public.company_data(org_number);
CREATE INDEX IF NOT EXISTS idx_company_data_crawled_at ON public.company_data(crawled_at);
CREATE INDEX IF NOT EXISTS idx_company_data_status ON public.company_data(status);
CREATE INDEX IF NOT EXISTS idx_company_data_company_name ON public.company_data USING gin(to_tsvector('swedish', company_name));

-- Create updated_at trigger
CREATE OR REPLACE FUNCTION public.handle_updated_at()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = NOW();
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER handle_company_data_updated_at
    BEFORE UPDATE ON public.company_data
    FOR EACH ROW
    EXECUTE FUNCTION public.handle_updated_at();

-- Add RLS (Row Level Security) policies
ALTER TABLE public.company_data ENABLE ROW LEVEL SECURITY;

-- Allow read access to all authenticated users
CREATE POLICY "Allow authenticated users to read company data"
    ON public.company_data FOR SELECT
    USING (auth.role() = 'authenticated');

-- Allow insert/update to all authenticated users
CREATE POLICY "Allow authenticated users to insert company data"
    ON public.company_data FOR INSERT
    WITH CHECK (auth.role() = 'authenticated');

CREATE POLICY "Allow authenticated users to update company data"
    ON public.company_data FOR UPDATE
    USING (auth.role() = 'authenticated');

-- Allow service role (for our Python client) full access
CREATE POLICY "Allow service role full access"
    ON public.company_data FOR ALL
    USING (auth.role() = 'service_role')
    WITH CHECK (auth.role() = 'service_role');
