PRAGMA foreign_keys = OFF;

DROP TABLE IF EXISTS Tickets;
DROP TABLE IF EXISTS Reservations;
DROP TABLE IF EXISTS Showings;
DROP TABLE IF EXISTS Movies;
DROP TABLE IF EXISTS Theaters;

PRAGMA foreign_keys = ON;

CREATE TABLE IF NOT EXISTS Users (
    username VARCHAR(50) PRIMARY KEY,
    name VARCHAR(100),
    address VARCHAR(255),
    telephone VARCHAR(20)
);

CREATE TABLE IF NOT EXISTS Theaters (
    theater_id SERIAL PRIMARY KEY,
    name VARCHAR(100) UNIQUE,
    total_seats INTEGER
);

CREATE TABLE IF NOT EXISTS Movies (
    movie_id SERIAL PRIMARY KEY,
    name VARCHAR(255) UNIQUE
);

CREATE TABLE IF NOT EXISTS Showings (
    showing_id SERIAL PRIMARY KEY,
    movie_id INTEGER REFERENCES Movies(movie_id),
    theater_id INTEGER REFERENCES Theaters(theater_id),
    show_date DATE,
    UNIQUE(movie_id, show_date)
);

CREATE TABLE IF NOT EXISTS Reservations (
    reservation_id SERIAL PRIMARY KEY,
    username VARCHAR(50) REFERENCES Users(username),
    showing_id INTEGER REFERENCES Showings(showing_id),
    reservation_number VARCHAR(50),
    FOREIGN KEY (showing_id, reservation_number) REFERENCES Tickets(showing_id, reservation_number)
);

CREATE TABLE IF NOT EXISTS Tickets (
    showing_id INTEGER REFERENCES Showings(showing_id),
    reservation_number VARCHAR(50),
    PRIMARY KEY (showing_id, reservation_number),
    FOREIGN KEY (showing_id, reservation_number) REFERENCES Reservations(showing_id, reservation_number)
);

INSERT INTO Theaters (name, total_seats) VALUES ('Theater 1', 100);
INSERT INTO Theaters (name, total_seats) VALUES ('Theater 2', 150);

INSERT INTO Movies (name) VALUES ('Movie 1');
INSERT INTO Movies (name) VALUES ('Movie 2');
INSERT INTO Movies (name) VALUES ('Movie 3');

INSERT INTO Showings (movie_id, theater_id, show_date) VALUES (1, 1, '2021-01-01');
INSERT INTO Showings (movie_id, theater_id, show_date) VALUES (1, 1, '2021-01-02');
INSERT INTO Showings (movie_id, theater_id, show_date) VALUES (1, 2, '2021-01-01');
INSERT INTO Showings (movie_id, theater_id, show_date) VALUES (2, 2, '2021-01-01');

INSERT INTO Users (username, name, address, telephone) VALUES ('user1', 'User 1', 'Address 1', '1234567890');
INSERT INTO Users (username, name, address, telephone) VALUES ('user2', 'User 2', 'Address 2', '1234567890');
INSERT INTO Users (username, name, address, telephone) VALUES ('user3', 'User 3', 'Address 3', '1234567890');